package com.yafengliang.fileupload.controller;

import com.yafengliang.fileupload.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author liangyafeng
 * @Description:
 * @date 2020/4/20 16:55
 */
@Controller
@Slf4j
@RequestMapping(value = "client")
public class FileUploadController {

    @RequestMapping(value = "/toImportFile")
    public ResponseEntity toImpl(MultipartFile fileUpload) {
        if (fileUpload != null) {
            try {
                BufferedReader br = null;
                StringBuffer sb;
                br = new BufferedReader(new InputStreamReader(fileUpload.getInputStream()));
                String temp = null;
                sb = new StringBuffer();
                try {
                    temp = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                while (temp != null) {
                    sb.append(temp + "\n");
                    try {
                        temp = br.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("upload success");
                return new ResponseEntity(new Result(null, true), HttpStatus.OK);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity(new Result(null, false), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            return new ResponseEntity(new Result(null, true), HttpStatus.FAILED_DEPENDENCY);
        }
    }

}
